

public class N002_addTwoNumbers {
    public static void main(String[] args) {

    }

//我的：
    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode result = null;
        ListNode tem = new ListNode(0);
        while(l1 != null || l2 != null){
            int a = l1!= null?l1.val:0;
            int b = l2!= null?l2.val:0;
            int sum = a+b;
            if(result ==null){
                int t = sum/10;
                sum = t>0?sum%10:sum;
                result = new ListNode(sum);
                tem.val = t;
            }else{
                sum +=tem.val;
                int t = sum/10;
                sum = t>0?sum%10:sum;
                //结果加入链表（尾插法）
                addNode(result, new ListNode(sum));
                tem = new ListNode(t);
            }
            l1=l1 !=null?l1.next:null;
            l2 =  l2!=null? l2.next:null;
        }
        if (tem.val > 0) {
            addNode(result, tem);
        }
        return result;
    }
    public static void addNode(ListNode result, ListNode newNode) {
        if (result.next == null) {
            result.next = newNode;
        }else {
            addNode(result.next, newNode);
        }
    }

///------------------------

    public  static  ListNode addTwoNumbers2(ListNode l1, ListNode l2) {
    return addTwoNumbers2(l1,l2,0);
}
    public static ListNode addTwoNumbers2(ListNode l1, ListNode l2,int a) {
        if(l1==null&&l2==null){return a==0?null:new ListNode(a);}
        if(l1 !=null){a += l1.val;l1 = l1.next;}
        if(l2 !=null){a += l2.val;l2 = l2.next;}
        return new ListNode(a%10,addTwoNumbers2(l1,l2,a/10));
    }


}
    class ListNode {
     int val;
      ListNode next;
      ListNode() {}
      ListNode(int val) { this.val = val; }
      ListNode(int val, ListNode next) { this.val = val; this.next = next; }
  }
